package com.xu.cloud.common.util;

import com.xu.cloud.common.constant.CodecConstant;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.Objects;

/**
 * MessageDigest摘要加密工具类
 *
 * @author xuguan
 * @since 2024/6/30
 */
public class MessageDigestUtil {

    static {
        final Provider provider = Providers.createBouncyCastleProvider();
        if (Objects.nonNull(provider)) {
            Security.addProvider(provider);
        }
    }

    public static byte[] encrypt(String message, String algorithm) {
        final MessageDigest messageDigest = getMessageDigest(algorithm);
        return messageDigest.digest(message.getBytes(CodecConstant.UTF_8));
    }

    public static String encryptToHex(String message, String algorithm) {
        return CodecUtil.hexString(encrypt(message, algorithm));
    }

    public static String encryptToBase64(String message, String algorithm) {
        return CodecUtil.base64EncodeString(encrypt(message, algorithm));
    }

    private static MessageDigest getMessageDigest(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("algorithm not support", e);
        }
    }
}
